$(function(){ 

    var $content = $('#content'); 
    //var log = console.log;   

    var FLAG = new Array();
    FLAG['FORM'] = false;
    FLAG['MEDIA'] = false;
    FLAG['TAGS'] = false;
    FLAG['PUBLISH'] = false;

    /***********************************************************
    * LOADERS
    ***********************************************************/    

    function loader()
    {
        $.modal(
        "<div><div class='animate'><img src='"+base_url+"assets/img/backgnds/loading.gif'></div><h2>Molim sačekajte...</h2></div>" , {
            closeHTML: "",
            containerCss:{
                height:70,
                width:120,
                borderColor:"#dedede"
            },
            opacity:20,
            overlayCss: {
                backgroundColor: "#000000"
            }
        });
    }

    /***********************************************************
    * Breadcamp prev - next
    ***********************************************************/

    function bc_next(){
        $content.find('ul.breadcrumb').wl_Breadcrumb('next');
    }

    function bc_prev(){
        $content.find('ul.breadcrumb').wl_Breadcrumb('prev'); 
    }

    $('.gDate').live('click',function(){

        /*Get date from DATEPICKER*/
        var chosen_date = $("#datumkomponenta").datepicker("getDate");        

        //show selected date before table
        var mesec = chosen_date.getMonth()+1;                             
        seldate = chosen_date.getDate() + "-" + mesec + "-" + chosen_date.getFullYear(); 

        publishdatetime = seldate+' '+$content.find('input.time').val();

        //log(publishdatetime)
    })

    $('#conf_category_tags').live('click',function(){

        var chk = $('#column').val();

        if(chk==0){

            $('#srvrserror-3').html('molimo odaberite kategoriju');
            $('#srvrserror-3').show('slow');

        }else {
            loader();

            $.ajax({
                type: "POST",
                url: base_url+'article/columns_tags',
                data: {
                    id: artId,  
                    subcolumn_id: $("#column").val(),  
                    tagovi: $("#tagovi").val()  
                },
                dataType: 'json',
                success: function(data){

                    if(data.action==true){

                        bc_next();   
                        $.modal.close();

                    }else{

                        alert('Molim odaberte sva polja.'+data.msg)

                    }


                }
            })
        }



    })

    /***********************************************************
    * FINISH
    ***********************************************************/

    $('#finish').live('click',function(){


        /***********************************************************
        * DATEPICKER 1 - POLUOBJAVA
        ***********************************************************/
        var chosen_date = $("#datumkomponenta1").datepicker("getDate");        

        //show selected date before table
        var mesec = chosen_date.getMonth()+1;                             
        seldate = chosen_date.getDate() + "-" + mesec + "-" + chosen_date.getFullYear(); 

        publishdatetimehalf = seldate+' '+$content.find('input.time1').val();


        /***********************************************************
        * DATEPICKER 2 - OBJAVA
        ***********************************************************/
        var chosen_date = $("#datumkomponenta2").datepicker("getDate");        

        //show selected date before table
        var mesec = chosen_date.getMonth()+1;                             
        seldate = chosen_date.getDate() + "-" + mesec + "-" + chosen_date.getFullYear(); 

        publishdatetime = seldate+' '+$content.find('input.time2').val();

        /***********************************************************
        * DATEPICKER 3 - TRAJE DO
        ***********************************************************/
        var chosen_date = $("#datumkomponenta3").datepicker("getDate");        

        //show selected date before table
        var mesec = chosen_date.getMonth()+1;                             
        seldate = chosen_date.getDate() + "-" + mesec + "-" + chosen_date.getFullYear(); 

        publishdatetimeend = seldate+' '+$content.find('input.time3').val();


        id = artId;

        loader();

        $.ajax({
            type: "POST",
            url: base_url+'article/finish',
            data: {
                id: id,
                publishmode: publishmode,
                publishdatetimehalf: publishdatetimehalf, 
                publishdatetime: publishdatetime, 
                publishdatetimeend: publishdatetimeend,
                articlestatus: $("#articlestatus").attr('checked')
            },
            dataType: 'json',
            success: function(data){

                if (data.action == true){

                    $.modal.close();

                    /*----------------------------------------------------------------------*/
                    /* go to preview article url 
                    /*----------------------------------------------------------------------*/
                    document.location.href = base_url + 'article/preview';
                    //document.location.href = base_url + 'article/preview_home?id='+id;


                }else{

                    alert("Error on server:"+data.msg)

                }


            }
        })

        return false;


    })

    /***********************************************************
    * HTML 1,2,3,4,5
    ***********************************************************/

    function setHtml1(){ 

        //return false; 

        //WYSIWYG Editor
        $content.find('textarea.html').wl_Editor({
            css: base_url+'assets/css/light/editor.css'
        });



        //The Form itself
        $content.find('#mainformart').wl_Form({
            submitButton: 'button.submit',
            resetButton: 'button.reset',
            method: 'post',
            action: null,
            ajax: true,
            serialize: false,
            parseQuery: true,
            dataType: 'text',
            status: true,
            sent: false,
            confirmSend: true,
            text: {
                required: 'Ovo polje je obavezno',
                valid: 'Ovo polje nije u redu',
                password: 'Lozinka je kratka',
                passwordmatch: 'Ovaa lozinka se ne poklapa',
                fileinqueue: 'Postoji najmanje jedan fajl na čekanju',
                incomplete: 'Molimo popunite formu ispravno!',
                send: 'pošalji formu...',
                sendagain: 'pošalji ponovo?',
                success: 'forma poslata!',
                error: 'greška prilikom slanja!',
                parseerror: 'Nemogu da deserializujem query string:\n %e'
            },
            tooltip: {
                gravity: 'nw'
            },
            onBeforePrepare: function () {

                $('#srvrserror-1').hide();

                loader();

                $.ajax({
                    type: "POST",
                    url: base_url+'article/f1',
                    data: {
                        uptitle: $('input[name=uptitle]').val(),
                        title: $('input[name=title]').val(),
                        title_home: $('input[name=title_home]').val(),
                        text: $("#text").wysiwyg("getContent"),
                        intro: $('input[name=intro]').val(),
                        tags: $('input[name=tags]').val(),
                        appmode: appmode,
                        id: artId,
                    },
                    dataType: 'json',
                    success: function(data){

                        if (data.action == true){

                            artId = data.id;                        

                            $('#srvrserror-1').hide();                            
                            $('#artId').val(artId);                            

                            appmode = 'edit';

                            bc_next();

                            $.modal.close();

                        }else{
                            artStsudId = -1;
                            $('#srvrserror-1').html(data.msg);
                            $('#srvrserror-1').show('slow');

                        }


                    }
                })

                return false;
            }
        }); 

    }

    function setHtml4(){

        /***********************************************************
        * TAGOVI
        ***********************************************************/

        $("select[multiple]").asmSelect({
            sortable: true,
            animate: true,
            addItemTarget: 'bottom'
        });

    }

    function setHtml5(){

        /***********************************************************
        * Datum komponenta
        ***********************************************************/
        date = new Date();
        selMonth = 0;
        selYear = 0;
        maxMounth = 0;

        // get the current date
        var minDate = new Date(date.getFullYear(), date.getMonth(), 1); //one day next before month
        var maxDate =  new Date(date.getFullYear(), date.getMonth() +1 + maxMounth, -0); // one day before next month

        $('#datumkomponenta1').html('');
        $('#datumkomponenta2').html('');
        $('#datumkomponenta3').html('');
        $('#datumkomponenta1').datepicker( "destroy" );
        $('#datumkomponenta2').datepicker( "destroy" );
        $('#datumkomponenta3').datepicker( "destroy" );

        $.datepicker.setDefaults($.datepicker.regional['sr']);

        $('#datumkomponenta1').datepicker({
            inline: true,
            hideIfNoPrevNext: true,
            minDate: minDate,
            dateFormat: 'dd.mm.yy',
            numberOfMonths: 1,
        });

        $("#time1").mask("99:99",{placeholder:"_"});

        $('#datumkomponenta2').datepicker({
            inline: true,
            hideIfNoPrevNext: true,
            minDate: minDate,
            dateFormat: 'dd.mm.yy',
            numberOfMonths: 1,
        });

        $("#time2").mask("99:99",{placeholder:"_"});

        $('#datumkomponenta3').datepicker({
            inline: true,
            hideIfNoPrevNext: true,
            minDate: minDate,
            dateFormat: 'dd.mm.yy',
            numberOfMonths: 1,
        });

        $("#time3").mask("99:99",{placeholder:"_"});

        //log('appmode:'+appmode)

        switch(publishmode){

            case 'edit':
                var dt = new Date( parseInt(publishdatetimehalf) * 1000);
                $('#datumkomponenta1').datepicker('setDate', new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()));
                var dt = new Date( parseInt(publishdatetime) * 1000); 
                $('#datumkomponenta2').datepicker('setDate', new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()));
                var dt = new Date( parseInt(publishdatetimeend) * 1000); 
                $('#datumkomponenta3').datepicker('setDate', new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()));
                break;

            case 'insert':
                $('#datumkomponenta1').datepicker('setDate', new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1));
                $('#datumkomponenta2').datepicker('setDate', new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1));
                $('#datumkomponenta3').datepicker('setDate', new Date(date.getFullYear()+10, date.getMonth(), date.getDate() + 1));
                break;
        }        

    }

    /*----------------------------------------------------------------------*/
    /* Breadcrumb
    /*----------------------------------------------------------------------*/

    $content.find('ul.breadcrumb').wl_Breadcrumb({
        start : 0,
        locked: false,
        disabled: false,
        onChange: function(element,id){
            switch(id){
                case 0: 
                //log('0')
                if(FLAG['FORM'] == false){
                    setHtml1();
                    FLAG['FORM'] = true;
                }
                break;
                case 1: 
                //log('1')
                if(FLAG['MEDIA'] == false){
                    /*setHtml2();
                    FLAG['MEDIA'] = true;*/
                }
                break;
                case 2: 
                //log('3')
                if(FLAG['TAGS'] == false){
                    setHtml4();
                    FLAG['TAGS'] = true;
                }
                break;
                case 3: 
                //log('4')
                if(FLAG['PUBLISH'] == false){
                    setHtml5();
                    FLAG['PUBLISH'] = true;
                }
                break;
            }
        }
    });

    //app start
    setHtml1();
    FLAG['FORM'] = true;

    $('#popuni').live('click', function(){

        $('input[name=uptitle]').val("Quisque loborti"); 
        $('input[name=title]').val("Nam enim risus"); 
        $('input[name=intro]').val("Phasellus pellentesque purus in massa"); 
        $("#text").wysiwyg("insertHtml", "Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis. Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui." ); 
    })

    var imageWriter = null;

    //$('#dialog').fadeIn('slow');

    //$('#popuni').trigger('click')
    $('.addImage').live('click', function(){

        imageWriter = this.id;
        $('#dialog').fadeIn('slow');
        $('.grid').hide();

    })

    $('.cropImage').live('click', function(){

        imageWriter = this.id;
        $('#cropHolder').fadeIn('slow');
        $('.grid').hide();
        //console.log(imageWriter) 
        var link = $('.imgHolder-'+imageWriter+' img').attr('src');
        //console.log(link) 
        var img = link.split("/");
        //console.log(img[img.length-1])

        //        Write data to crop html  
        $('#original_image_name').val(img[img.length-1]);
        $('#target').attr('src', base_url+'tempatt/'+img[img.length-1]);

        initializeCropPlugin();

    })

    var jcrop_api;
    var img_width;
    var img_height;

    function initializeCropPlugin(){




        $('#target').Jcrop({
            onChange: showCoords,
            onSelect: showCoords
        },function(){
            jcrop_api = this;

            img_width = $('#target').width();
            img_height = $('#target').height();
            
            x1 = (img_width - 482) / 2;
            y1 = (img_height - 321) / 2;

            x2 = x1 + 482;
            y2 = y1 + 321;

            jcrop_api.animateTo([ x1,y1,x2,y2 ]);
        });

    }

    function showCoords(c)
    {
        $('#x1').val(c.x);
        $('#y1').val(c.y);
        $('#x2').val(c.x2);
        $('#y2').val(c.y2);
        $('#w').val(c.w);
        $('#h').val(c.h);
        //console.log('x1:'+c.x+' y1:'+c.y+' x2:'+c.x2+' y2:'+c.y2+' w:'+c.w+' h:'+c.h);

    };

    $("input[name='cropDim[]']").change(function(){

        var val = $(this).val();
        var arr = val.split('x');
        var width = arr[0];
        var height = arr[1];

        /*CENTER SELECTION*/
        x1 = (img_width - width) / 2;
        y1 = (img_height - height) / 2;

        x2 = parseInt(x1) + parseInt(width);
        y2 = parseInt(y1) + parseInt(height);

        ///console.log('x1:'+x1+' y1:'+y1+' x2:'+x2+' y2:'+y2+' w:'+width+' h:'+height);
        jcrop_api.animateTo([ x1,y1,x2,y2 ]);

        return false;
    });

    $('#closeDialog').live('click', function(){

        $('#dialog').hide();
        $('.grid').fadeIn('slow'); 

    })

    $('#c_thumb').live('click', function(){
        //console.log('click');
        $('#cropHolder').hide();
        $('.grid').fadeIn('slow');
        jcrop_api.destroy();
        return false; 

    })

    $('#dodajRed').live('click', function(){

        rowCount++;

        var html = '<tr id="mg-img-'+rowCount+'">'+
        '<td class="logoHolder-'+rowCount+'" style="text-align: center;">No media</td>'+
        '<td class="imgHolder-'+rowCount+'" style="vertical-align: middle; text-align:center;">No preview</td>'+
        '<input type="hidden" name="img[]" id="img-'+rowCount+'" value="" class="emptyChecker" />'+
        '<td><input type="text" name="caption[]" id="caption-'+rowCount+'" style="width: 190px;" /></td>'+
        '<td><input type="checkbox" name="main_img[]" id="main_img-'+rowCount+'" class="glavna" value="" /></td>'+
        '<td><input type="text" name="sort[]" id="sort-'+rowCount+'" style="width: 80px;" value="'+rowCount+'" /></td>'+
        '<td style="text-align:center;"><input type="radio" name="img_pos[]'+rowCount+'" value="left"></td>'+
        '<td style="text-align:center;"><input type="radio" name="img_pos[]'+rowCount+'" checked="checked" value="center"></td>'+
        '<td style="text-align:center;"><input type="radio" name="img_pos[]'+rowCount+'" value="right"></td>'+
        '<td style="text-align:center;"><a href="javascript:" id="'+rowCount+'" class="addImage">Dodaj mediju</a></td>'+
        '<td style="text-align:center;"><a href="javascript:" class="ukloniRed">Ukloni red</a></td>'+
        '</tr>' ;

        $('#media_gallery_content_grid tbody').append(html);


    })

    $('.ukloniRed').live('click', function(){

        /*rowCount--;*/
        $(this).parent().parent().fadeOut('slow', function(){
            $(this).remove()
        });

    })

    $('#next_2').live('click', function(){

        //loader();

        var condition = false;

        $('.emptyChecker').each(function(index){
            if($(this).val() != '') condition = true;
        });        

        if(condition == false){
            $('#srvrserror-2').html('Molim odabreite barem jednu mediju.')
            $('#srvrserror-2').show();
            return false;
        }else{
            $('#srvrserror-2').hide();  
        }

        $.ajax({
            type: "POST",
            url: base_url+'article/mediaGallery',
            data: $('#mediaGallery').serialize(),                
            dataType: 'json',
            success: function(data){

                bc_next();

            }
        })    

    })

    $('.chooseImage').live('click', function(){

        //log($(this).attr('key'));

        $('.logoHolder-'+imageWriter).html('<img src="'+base_url+'assets/img/img-logo.png" height="23" />');
        $('.imgHolder-'+imageWriter).html('<img src="'+base_url+'tempatt/'+$(this).attr('key')+'" height="23" />');

        $('#dialog').hide();
        $('.grid').fadeIn('slow'); 
        $('#'+imageWriter).html('Promjeni');

        //        Add Crop Element only if not alredy exists
        var countElem = $('#'+imageWriter).parent().find( 'a' ).length;
        //console.log(countElem)
        if(countElem<2){
            //rowCount++;
            $('#'+imageWriter).parent().append(' <span class="removeSpace">|</span> <a href="javascript:" id="'+imageWriter+'" class="cropImage">Kropuj</a> ');
        }


        $('#img-'+imageWriter).val($(this).attr('id'));

    });

    $('.chooseYT').live('click', function(){

        //log($(this).attr('key'));

        $('.logoHolder-'+imageWriter).html('<img src="'+base_url+'assets/img/yt-logo.png" height="23" />');
        $('.imgHolder-'+imageWriter).html('<img src="http://img.youtube.com/vi/'+$(this).attr('key')+'/0.jpg" height="23" />');

        $('#dialog').hide();
        $('.grid').fadeIn('slow'); 
        $('#'+imageWriter).html('Promjeni mediju');

        //        Add Crop Element only if not alredy exists
        var countElem = $('#'+imageWriter).parent().find( 'a' ).length;
        //console.log(countElem)
        if(countElem==2){
            $('#'+imageWriter).parent().find('.removeSpace').remove();
            //.remove();
            //$('#'+imageWriter).parent().text(($('#'+imageWriter).parent().text().replace('|',' ')));
            $('#'+imageWriter).parent().find( 'a.cropImage' ).remove();
        }

        $('#img-'+imageWriter).val($(this).attr('id'));

    });

    /*----------------------------------------------------------------------*/
    /* datatable plugin
    /*----------------------------------------------------------------------*/

    $content.find("table.datatable").dataTable({
        "sPaginationType": "two_button",
        "oLanguage": {
            "sLengthMenu": "Prikaži _MENU_ članaka po strani",
            "sZeroRecords": "Nema podataka - !",
            "sInfo": "Prikazujem _START_ - _END_ od _TOTAL_ članaka",
            "sInfoEmpty": "Prikazujem 0 do 0 od 0 članaka",
            "sInfoFiltered": "(filtritam od _MAX_ ukupnih članaka)"
        },
        "aoColumnDefs": [ 
        { "bSortable": false, "aTargets": [0,null,2,null,null,null,null,7] }
        ],
        "iDisplayLength" : "25",
        "aaSorting": [[ 4, "desc" ]] 
    });

    $('#directory').live('change', function(){

        if($(this).val()==0) return false;

        loader();

        var id = $(this).val();

        $.ajax({
            type: "POST",
            url: base_url+'media/getMediaByFolder',
            data: {
                id: id,
                who: 'article'
            },
            dataType: 'json',
            success: function(data){

                if (data.action == true){

                    $('.ex_highlight_row').html('');                 

                    $('.ex_highlight_row').append(data.html);


                    /*----------------------------------------------------------------------*/
                    /* datatable plugin
                    /*----------------------------------------------------------------------*/

                    $content.find("table.datatable").dataTable({
                        "sPaginationType": "two_button",
                        "oLanguage": {
                            "sLengthMenu": "Prikaži _MENU_ medija po strani",
                            "sZeroRecords": "Nema podataka - !",
                            "sInfo": "Prikazujem _START_ - _END_ od _TOTAL_ medija",
                            "sInfoEmpty": "Prikazujem 0 do 0 od 0 članaka",
                            "sInfoFiltered": "(filtritam od _MAX_ ukupnih medija)"
                        },
                        "aoColumnDefs": [ 
                        { "bSortable": false, "aTargets": [0,null,2,null,null,null,null,7] }
                        ],
                        "iDisplayLength" : "25",
                        "aaSorting": [[ 4, "desc" ]] 
                    });

                    $('<div class="dataTables_dir">'+$('#example_dir').html()+'</div>').insertAfter('#example_length');

                    $.modal.close(); 

                }else if (data.action == false){

                    alert(data.msg)

                    $('#directory').val(0);

                    $.modal.close();

                }else alert("Error on server:"+data.msg);


            }
        })

        return false;

    })

    $('#directory').val(0); 

    $('<div class="dataTables_dir">'+$('#example_dir').html()+'</div>').insertAfter('#example_length');

    $('input[name=title]').keyup(function() {
        $('h1').text($(this).val());
        switch(publishmode){

            case 'edit':
                if($('h1').text()=='')$('h1').text('Ažuriranje članka');
                break;

            case 'insert':
                if($('h1').text()=='')$('h1').text('Novi članak');
                break;

        }
    });

    var last_str = ""

    $('input[name=title_home]').keyup(function() {
        str = $(this).val();
        cnt = str.length;
        left = 43-parseInt(cnt);

        if(left<=0){
            alert ('Previse karaktera!')
            $(this).val(last_str);
            return false;
        }else{
            $('#title_home_chars').html(left);
            last_str = str; 
        }



    });  

    $('#save_thumb').live('click', function(){

        $.ajax({
            type: "POST",
            url: base_url+'crop/saveThumbnail',
            data: $('#thumbnail').serialize(),
            dataType: 'json',
            success: function(data){

                if(data.action==true){

                    //Replace photo ande MadiaId
                    replaceFhotoAndData(data.mediaId, data.fileName);

                    $('#c_thumb').trigger('click');


                    logm('Uspješno ste kreirali thumbnail.')

                }else{

                    alert('Molim odaberte sva polja.'+data.msg)

                }


            }
        })

    })

    function logm($msg){

        $('#logm').html($msg);
        $('#logm').fadeIn('slow');

        $('html, body').animate({
            scrollTop: $("#logm").offset().top
        }, 500);


        //setTimeout("$('#logm').fadeOut(function(){$(this).remove();})",2300);
        setTimeout("$('#logm').fadeOut(function(){})",2300);
    }

    function replaceFhotoAndData(mediaId, filename){
        /*console.log(imageWriter)
        console.log(mediaId+':'+filename)*/
        $('#img-'+imageWriter).val(mediaId);
        $('.imgHolder-'+imageWriter+' img').attr('src', base_url+'tempatt/'+filename);
    }

    if(appmode=='insert'){
        $('.glavna').each(function(){
            $(this).attr('checked',false);
        })
    }

    $('.glavna').change(function() {
        if($(this).attr('checked')=='checked'){
            //log('checked')
            var id = this.id.split("-");
            $('#sort-'+id[1]).val("");
        }else{
            //log('unchecked') 
            var id = this.id.split("-");
            $('#sort-'+id[1]).val("");
        }

    });

    var showChars = function (){

        $('#cntChar').html($(this).val().length);

    }
    
    var showCharsM = function (){

        $('#cntCharMedia').html($(this).val().length);

    }

    $("#uptitle").live('keyup', showChars);
    $("#uptitle").live('focus', showChars);
    $('input[name=title]').live('keyup', showChars);
    $('input[name=title]').live('focus', showChars);
    $('input[name=title_home]').live('keyup', showChars);
    $('input[name=title_home]').live('focus', showChars);
    $('input[name=intro]').live('keyup', showChars);
    $('input[name=intro]').live('focus', showChars);
    $('input[name=text]').live('keyup', showChars);
    $('input[name=text]').live('focus', showChars);
    
    for(var i=0; i<99; i++){
        
        $('#caption-'+i).live('keyup', showCharsM);
        $('#caption-'+i).live('focus', showCharsM);
    }
}); 
